<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>原生Http实现cookie设置 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="前言说起Cookie要从Http说起，因为http无状态的,即客户端每次发起一个请求都是独立的,上一个会话与下一会话没有关系。为了让每次请求有状态，都给请求增加一个cookie，相当于每次请求都会有一个标识。 cookie  由服务器发送给客户端（浏览器）的小量信息，以{key：value}的形式存在。可以由后端、前端设置。注：ajax不支持cookie跨域">
<meta property="og:type" content="article">
<meta property="og:title" content="原生Http实现cookie设置">
<meta property="og:url" content="http://yoursite.com/2020/07/25/%E5%8E%9F%E7%94%9FHttp%E5%AE%9E%E7%8E%B0cookie%E8%AE%BE%E7%BD%AE/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="前言说起Cookie要从Http说起，因为http无状态的,即客户端每次发起一个请求都是独立的,上一个会话与下一会话没有关系。为了让每次请求有状态，都给请求增加一个cookie，相当于每次请求都会有一个标识。 cookie  由服务器发送给客户端（浏览器）的小量信息，以{key：value}的形式存在。可以由后端、前端设置。注：ajax不支持cookie跨域">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-07-25T11:50:22.000Z">
<meta property="article:modified_time" content="2020-07-30T13:04:01.659Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="node">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 5.0.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-原生Http实现cookie设置" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2020/07/25/%E5%8E%9F%E7%94%9FHttp%E5%AE%9E%E7%8E%B0cookie%E8%AE%BE%E7%BD%AE/" class="article-date">
  <time datetime="2020-07-25T11:50:22.000Z" itemprop="datePublished">2020-07-25</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      原生Http实现cookie设置
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h5><p>说起Cookie要从Http说起，因为http无状态的,即客户端每次发起一个请求都是独立的,上一个会话与下一会话没有关系。为了让每次请求有状态，都给请求增加一个cookie，相当于每次请求都会有一个标识。</p>
<h5 id="cookie"><a href="#cookie" class="headerlink" title="cookie"></a>cookie</h5><p>  由服务器发送给客户端（浏览器）的小量信息，以{key：value}的形式存在。可以由后端、前端设置。<code>注</code>：ajax不支持cookie跨域<br>  <a id="more"></a></p>
<h5 id="cookie-属性"><a href="#cookie-属性" class="headerlink" title="cookie 属性"></a>cookie 属性</h5><ul>
<li>name ,value<br>name是cookie的名字，Cookie一旦创建，名称便不可更改,value为cookie的值</li>
<li>domain<br>可以访问该Cookie的域名。如果设置为“.baidu.com”，则所有以“baidu.com”结尾的域名都可以访问该Cookie；第一个字符必须为“.”</li>
<li>maxAge 、expires<br>maxAge为Cookie失效的相对时间，例如：max-age=10 单位秒。<br>expires为Cookie失效的具体时间<ul>
<li>path<br>该Cookie的使用路径。例如：<br>path=/，说明本域名下的路径都可以访问该Cookie。<br>path=/app/，则只有路径为“/app”的程序可以访问该Cookie</li>
<li>isHttpOnly<br>HttpOnly属性是用来限制非HTTP协议程序接口对客户端Cookie进行访问</li>
</ul>
</li>
</ul>
<p><code> 如果不设置 domain/path 每次请求都会带上cookie</code><br><code> cookie的限制为4k 由于cookie是在客户端 不安全（容易被篡改，被人拦截）</code><br>  下来我用node实现一下<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http =  <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"> <span class="keyword">let</span> server = http.createServer(<span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line"></span><br><span class="line">     <span class="keyword">if</span>(req.url ===<span class="string">&#x27;/write&#x27;</span>)&#123;</span><br><span class="line">      <span class="comment">//key ,value</span></span><br><span class="line">      <span class="comment">//domain 限制某个域可以访问</span></span><br><span class="line">      <span class="comment">//path 在哪个路径下可以访问 /表示任何路径都可以</span></span><br><span class="line">      <span class="comment">//expires/max-age</span></span><br><span class="line">      <span class="comment">//httpOnly 是否服务端设置后 前端不能更改</span></span><br><span class="line">      res.setHeader(<span class="string">&#x27;Set-Cookie&#x27;</span>,[<span class="string">&#x27;name=zf;path=/&#x27;</span>,<span class="string">&#x27;age=10;httpOnly=true&#x27;</span>])</span><br><span class="line">      res.end(<span class="string">&#x27;write ok&#x27;</span>)</span><br><span class="line">     &#125;<span class="keyword">else</span> <span class="keyword">if</span>(req.url ===<span class="string">&#x27;/read&#x27;</span>)&#123;</span><br><span class="line">    res.end(req.headers.cookie||<span class="string">&#x27;empty&#x27;</span>);</span><br><span class="line">     &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">         res.end(<span class="string">&#x27;not found&#x27;</span>);</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line"> &#125;)</span><br><span class="line">server.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure><br>像上面 <code>res.setHeader(&#39;Set-Cookie&#39;,[&#39;name=zf;path=/&#39;,&#39;age=10;httpOnly=true&#39;])</code> 如果我们有100个cookie我们是不是需要写一个数组，这样的话就显得更加麻烦。下面我来重新改写一下，让它看起来更流畅</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http =  <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> server = http.createServer(<span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line"> <span class="keyword">let</span> arr = [];</span><br><span class="line"> <span class="comment">//res.setCookie 方法类似中间鉴，而且每次setCookie时都会属性值合并到arr数组中，这样就比之前更容易理解</span></span><br><span class="line">  res.setCookie = <span class="function"><span class="keyword">function</span>(<span class="params">key ,value,options=&#123;&#125;</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">let</span> opts = []</span><br><span class="line">      <span class="keyword">if</span>(options.domain)&#123;</span><br><span class="line">        opts.push(<span class="string">`domain=<span class="subst">$&#123;options.domain&#125;</span>`</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span>(options.path)&#123;</span><br><span class="line">          opts.push(<span class="string">`path=<span class="subst">$&#123;optins.path&#125;</span>`</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span>(optins.maxAge)&#123;</span><br><span class="line">          opts.push(<span class="string">`max-age=<span class="subst">$&#123;optios.maxAge&#125;</span>`</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span>(optins.expires)&#123;</span><br><span class="line">        opts.push(<span class="string">`expires=<span class="subst">$&#123;optios.expires.toGMTString()&#125;</span>`</span>)</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span>(options.httpOnly)&#123;</span><br><span class="line">          options.push(<span class="string">`httpOnly=<span class="subst">$&#123;optios.httpOnly&#125;</span>`</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      arr.push(<span class="string">`<span class="subst">$&#123;key&#125;</span>=<span class="subst">$&#123;value&#125;</span>;<span class="subst">$&#123;opts.join(<span class="string">&#x27;; &#x27;</span>)&#125;</span>`</span>)</span><br><span class="line">      res.setHeader(<span class="string">&#x27;Set-Cookie&#x27;</span>,arr)</span><br><span class="line">  &#125;&#125;</span><br><span class="line">     <span class="keyword">if</span>(req.url ===<span class="string">&#x27;/write&#x27;</span>)&#123;</span><br><span class="line">      <span class="comment">//key ,value</span></span><br><span class="line">      <span class="comment">//domain 限制某个域可以访问</span></span><br><span class="line">      <span class="comment">//path 在哪个路径下可以访问</span></span><br><span class="line">      <span class="comment">//expires/max-age</span></span><br><span class="line">      <span class="comment">//httpOnly 是否服务端设置后 前端不能更改</span></span><br><span class="line">      res.setCookie(<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;zhu&#x27;</span>,&#123;</span><br><span class="line">          domain:<span class="string">&#x27;/&#x27;</span>,</span><br><span class="line">          path:<span class="string">&#x27;/&#x27;</span>,</span><br><span class="line">          maxAge:<span class="number">10</span></span><br><span class="line">      &#125;);</span><br><span class="line">      res.end(<span class="string">&#x27;write ok&#x27;</span>)</span><br><span class="line">     &#125;<span class="keyword">else</span> <span class="keyword">if</span>(req.url ===<span class="string">&#x27;/read&#x27;</span>)&#123;</span><br><span class="line"></span><br><span class="line">     &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">         res.end(<span class="string">&#x27;not found&#x27;</span>);</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line"> &#125;);</span><br><span class="line">server.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>
<p>Koa的设置cookie也是基于这样方式的，是不是设置起来更容易流畅了呢</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2020/07/25/%E5%8E%9F%E7%94%9FHttp%E5%AE%9E%E7%8E%B0cookie%E8%AE%BE%E7%BD%AE/" data-id="ckd8udtc0000k9gt48whzbs6y" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/node/" rel="tag">node</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/07/30/hello-world/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          我的第一章博客
        
      </div>
    </a>
  
  
    <a href="/2020/07/23/%E5%B0%81%E8%A3%85Vue%E7%BB%84%E4%BB%B6%E5%B0%86%E4%BB%BB%E6%84%8F%E5%90%8E%E7%BC%80%E6%96%87%E4%BB%B6%E7%9B%AE%E5%BD%95%E7%BB%9F%E4%B8%80%E5%85%A8%E9%83%A8%E5%BC%95%E5%85%A5%E5%88%B0%E5%BD%93%E5%89%8D%E6%96%87%E4%BB%B6/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">封装Vue组件将任意后缀文件目录统一全部引入到当前文件</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue/" rel="tag">Vue</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue%E5%85%A8%E5%AE%B6%E6%A1%B6/" rel="tag">Vue全家桶</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/js/" rel="tag">js</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/node/" rel="tag">node</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Vue/" style="font-size: 20px;">Vue</a> <a href="/tags/Vue%E5%85%A8%E5%AE%B6%E6%A1%B6/" style="font-size: 10px;">Vue全家桶</a> <a href="/tags/js/" style="font-size: 15px;">js</a> <a href="/tags/node/" style="font-size: 10px;">node</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/07/">July 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/06/">June 2020</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2020/07/30/hello-world/">我的第一章博客</a>
          </li>
        
          <li>
            <a href="/2020/07/25/%E5%8E%9F%E7%94%9FHttp%E5%AE%9E%E7%8E%B0cookie%E8%AE%BE%E7%BD%AE/">原生Http实现cookie设置</a>
          </li>
        
          <li>
            <a href="/2020/07/23/%E5%B0%81%E8%A3%85Vue%E7%BB%84%E4%BB%B6%E5%B0%86%E4%BB%BB%E6%84%8F%E5%90%8E%E7%BC%80%E6%96%87%E4%BB%B6%E7%9B%AE%E5%BD%95%E7%BB%9F%E4%B8%80%E5%85%A8%E9%83%A8%E5%BC%95%E5%85%A5%E5%88%B0%E5%BD%93%E5%89%8D%E6%96%87%E4%BB%B6/">封装Vue组件将任意后缀文件目录统一全部引入到当前文件</a>
          </li>
        
          <li>
            <a href="/2020/07/15/js%E4%B8%AD%E7%9A%84%E9%98%B2%E6%8A%96%E4%B8%8E%E8%8A%82%E6%B5%81/">js中的防抖与节流</a>
          </li>
        
          <li>
            <a href="/2020/07/07/%E6%89%8B%E5%8A%A8%E5%AE%9E%E7%8E%B0call%EF%BC%8Capply,bind/">手动实现call，apply,bind</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2020 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css">

  
<script src="/fancybox/jquery.fancybox.pack.js"></script>




<script src="/js/script.js"></script>




  </div>
</body>
</html>